function [pX,pY,OD] = ProcessImage(hdfFilePath,autoROI,userROI,doFitData,stopPlot)

% [pX,pY,OD] = ProcessImage(hdfFilePath,autoROI,userROI,doFitData)
% Finds Gaussian-shaped signals on fluorescence or absorption images.
% Returns:
% pX - The parameters for a Gaussian fit to the data in the x (vertical)
% direction.
% pX(1) = Gaussian amplitude
% pX(2) = Peak position (in units of image pixels)
% pX(3) = Standard deviation (in units of image pixels)
% pX(4) = Offset
% pY - Same description as pX
% OD - The image (OD if it's an absorption image, raw image for a fluor.).

% expp = ExpParams();
cons = Constants();

% img_time = 100e-6;

% y = double(h5read(hdfFilePath,'/Image/image'));

y = cast(h5read(hdfFilePath,'/Image/image'),'double')/4; % Divide by 4 as 14-bit data from camera is multiplied by 4 (presumably when cast as a 16-bit integer).
img_var = h5read(hdfFilePath,'/Image/configuration');
img_time = h5read(hdfFilePath,'/Image/exposuretime');
type_img = h5read(hdfFilePath,'/Image/typeimaging');

expp = ParamImgSys(GetImgConfig(img_var));

dim = size(y);
abs = 0;

% Filter image to find ROI
N = 60;
sig = 30;
ovflw = 'no';

% max(max(y(:,:,1)))  %ERASE LATER
% min(min(y(:,:,1)))  %ERASE LATER

if size(dim,2) == 3 % Absorption
    num = y(:,:,1);% - y(:,:,3);
    den = y(:,:,2);% - y(:,:,3);
    maxcntN = max(max(num));
    maxcntD = max(max(den));
    if maxcntN > 2^14 || maxcntD > 2^14
        ovflw = 'yes';
    end
    den(den==0) = 1;
    ODlin = (num./den)';
    
    OD = -log(ODlin);
    OD(isinf(OD)) = 0;
    OD(isnan(OD)) = 0;
    OD = real(OD);
    OD = OD - mean(mean(OD));
    %     OD = y(:,:,1);
elseif size(dim,2) == 2 % Fluorescence
    OD = y';
    OD = OD - mean(mean(OD));
else
    error('Can''t determine imaging method');
end

ODfilt = conv2(OD,gaussian2d(N,sig),'same'); % Low-pass filter image

yC = 1:expp.short_px_nb;
xC = 1:expp.long_px_nb;

if autoROI
    % Find ROI and extract first approx. signal from filtered image.
    mx = max(max(ODfilt));
    [I,J] = find(ODfilt == mx);
    wndw = 50;
    
    ROI(1) = I(1);
    ROI(2) = J(1);
    
    yIntFilt = sum(ODfilt(:,ROI(2)-wndw:ROI(2)+wndw),2);
    xIntFilt = sum(ODfilt(ROI(1)-wndw:ROI(1)+wndw,:),1);
    
    ampGuessY = max(yIntFilt) - min(yIntFilt);
    ampGuessX = max(xIntFilt) - min(xIntFilt);
    
    options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
    pYtmp = fminsearch(@(p)FitGauss(p,yC,yIntFilt),[ampGuessY ROI(1) 100 min(yIntFilt)],options);
    pXtmp = fminsearch(@(p)FitGauss(p,xC,xIntFilt'),[ampGuessX ROI(2) 100 min(xIntFilt)],options);
    
    % Use data from filtered image to extract data from raw image.
    sigmas = 3;
    xWndw = round(sigmas*pXtmp(3));
    yWndw = round(sigmas*pYtmp(3));
    xROI = ROI(2)-xWndw:ROI(2)+xWndw;
    yROI = ROI(1)-yWndw:ROI(1)+yWndw;
    
    % Remove parts of the ROI if it goes outside of the photo.
    if min(xROI) < 1
        xROI = xROI(xROI > 0);
    end
    if min(yROI) < 1
        yROI = yROI(yROI > 0);
    end
    
    if max(yROI) > expp.short_px_nb
        yROI = yROI(yROI < expp.short_px_nb + 1);
    end
    if max(xROI) > expp.long_px_nb
        xROI = xROI(xROI < expp.long_px_nb + 1);
    end
    
    yInt = sum(OD(yROI,xROI),2);
    xInt = sum(OD(yROI,xROI),1);
    
else
    % Use user-input ROI parameters to guess initial fitting parameters
    yROI = userROI(3):userROI(4);
    xROI = userROI(1):userROI(2);
    
    yInt = sum(OD(yROI,xROI),2);
    xInt = sum(OD(yROI,xROI),1);
    
    pYtmp(1) = max(yInt) - min(yInt);
    pXtmp(1) = max(xInt) - min(xInt);
    
    pYtmp(2:3) = [mean(userROI(3:4)) 150];
    pXtmp(2:3) = [mean(userROI(1:2)) 150];
end

if doFitData
    
    options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
    pY = fminsearch(@(p)FitGauss(p,yROI,yInt),[pYtmp(1:3) min(yInt)],options);
    pX = fminsearch(@(p)FitGauss(p,xROI,xInt'),[pXtmp(1:3) min(xInt)],options);
    
else
    pY = zeros(1,4);
    pX = pY;
end

% Estimate number of atoms using camera
amp = (pX(1) + pY(1))/2; % Take mean amplitude of two Gaussian fits.
% capture_fraction = 0.5*(1 - sqrt(1 - (expp.na_telec)^2)); % fraction of total light captured by lens ( ~ 0.5 %)
total_num_electrons = amp*sqrt(2*pi)*mean([pX(3) pY(3)]);
total_photons = total_num_electrons/expp.coll_eff;
num_atoms = 2*total_photons/(img_time*cons.Gamma); % num_atoms = (num_photons/time) / (scattering rate)

% Give the width as the std deviation in um
px_size = 6.45; % um
mag = expp.mag; % magnification
widthYum = (pY(3))*px_size/mag;
widthXum = (pX(3))*px_size/mag;

if ~exist('stopPlot','var')
    
    figure(1)
    subplot(3,3,[1 2 4 5])
    oneMat = ones(size(OD));
    zeroMat = nan(size(OD));
    zeroMat(yROI,xROI) = 1;
    ODwindow = OD.*zeroMat;
    imagesc(ODwindow);
    % imagesc((ODfilt));
    line([xROI(1) xROI(end)],[yROI(1) yROI(1)])
    line([xROI(1) xROI(1)],[yROI(1) yROI(end)])
    line([xROI(end) xROI(end)],[yROI(1) yROI(end)])
    line([xROI(1) xROI(end)],[yROI(end) yROI(end)])
    axis equal
    xlims = xlim;
    ylims = ylim;
    
    subplot(3,3,[3 6])
    plot(yInt,yROI,gauss(pY,yC),yC);
    set(gca,'YDir','reverse');
    ylim(ylims);
    
    subplot(3,3,[7 8])
    plot(xROI,xInt,xC,gauss(pX,xC));
    xlim(xlims);
    
    h = subplot(3,3,9,'Visible', 'off');
    cla(h);
    text(0, .5, sprintf('%s\n%s\n%s\n%s\n%s', ...
        ['v-width (um): ' num2str(widthXum)], ['h-width (um): ' num2str(widthYum)], ...
        ['peak(v,h) = (' num2str(round(pX(2))) ',' num2str(round(pY(2))) ')'], ...
        ['Na = ' num2str(num_atoms,'%e')], ...
        ['Bin ovflw warning = ' ovflw]), ...
        'VerticalAlignment', 'middle', ...
        'FontName', 'Courier New', ...
        'FontWeight', 'bold', ...
        'FontSize', 20);
    
end



% cnt = numel(y(:,:,2));
%
% sigAt = reshape(y(:,:,1),1,cnt); % signal with atoms
% sigBK = reshape(y(:,:,2),1,cnt); % background signal (no atoms)
%
% [Nat,pAt] = hist(sigAt,100);
% [Nbk,pBK] = hist(sigBK,100);
%
% figure(2)
% plot(pAt,Nat,pBK,Nbk)
%
% figure(3)
% imagesc(y(:,:,1))